<template>
	<view class="container ">
		<!-- <u-loading-page :loading="true" loading-text="加载中"></u-loading-page> -->
		<view class="content">
			<!-- 车牌号 -->
			<view class="info-input">
				<view class="img">
					<image class="pic" src='https://peixin.peiyu.online/xmk/images/车牌号码.png' mode="heightFix"></image>
				</view>
				<view class="ipt">
					<input placeholder="请输入车牌号"
						placeholder-style="font-family: Alibaba_PuHuiTi_Thin;font-weight: 250;color: $border-color"
						:focus="false" @tap="onFocus" v-model="plate" disabled />
					<!-- <text class="txt" @click="temporary">临时牌照</text> -->
					<image class="pic" src="https://peixin.peiyu.online/xmk/images/相机.png" mode="heightFix"
						@click="isPlatePhoto=true">
					</image>
				</view>
			</view>
			<!-- 用户名 -->
			<view class="info-input">
				<view class="img">
					<image class="pic" src="https://peixin.peiyu.online/xmk/images/默认头像.png" mode="heightFix"></image>
				</view>
				<view class="ipt">
					<input placeholder="请输入客户姓名"
						placeholder-style="font-family: Alibaba_PuHuiTi_Thin;font-weight: 250;color: $border-color"
						v-model="name" />
				</view>
			</view>
			<!-- 手机号 -->
			<view class="info-input">
				<view class="img">
					<image class="pic" src="https://peixin.peiyu.online/xmk/images/手机号码.png" mode="heightFix"></image>
				</view>
				<view class="ipt">
					<input placeholder="请输入客户手机号"
						placeholder-style="font-family: Alibaba_PuHuiTi_Thin;font-weight: 250;color: $border-color"
						v-model="phone" />
				</view>
			</view>
			<!-- 车架号 -->
			<view class="info-input">
				<view class="img">
					<image class="pic" src="https://peixin.peiyu.online/xmk/images/汽车.png" mode="heightFix"></image>
				</view>
				<view class="ipt">
					<input placeholder="请输入车架号"
						placeholder-style="font-family: Alibaba_PuHuiTi_Thin;font-weight: 250;color: $border-color"
						v-model="vin" />
					<image class="pic" src="https://peixin.peiyu.online/xmk/images/相机.png" mode="heightFix"
						@click="isVinPhoto=true">
					</image>
				</view>
			</view>

			<button class="btn" @click="to_next">确定</button>
		</view>

		<u-keyboard ref="uKeyboard" mode="car" :show="keyboardShow" @change="valChange" @backspace="backspace"
			safeAreaInsetBottom @close="close" @confirm="confirm" @cancel="cancel"></u-keyboard>

		<!-- 拍摄车架号相机 -->
		<camera-car type="vin" v-if="isVinPhoto" @onConfirm="onConfirmCameraVIN" @cancel="onCancel"></camera-car>
		<!-- 拍摄车牌号相机 -->
		<camera-car type="plate" v-if="isPlatePhoto" @onConfirm="onConfirmCameraPlate" @cancel="onCancel"></camera-car>
	</view>

</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		onLoad,
		onShow,
	} from "@dcloudio/uni-app"
	import {
		useMainStore
	} from '@/utils/store.js';
	import {
		api_get_vin
	} from "../../../apis/get_vin.js";
	import {
		api_get_plate
	} from "../../../apis/get_plate.js";
	import {
		api_saleOrder_add,
		api_saleOrder_delete
	} from "../../../apis/apis.js"


	const keyboardShow = ref(false);
	const name = ref("");
	const phone = ref("");
	const isVinPhoto = ref(false); //是否开始拍照(车架号)
	const isPlatePhoto = ref(false); //是否开始拍照(车牌号)
	const vin = ref(""); //车架号
	const plate = ref(""); //车牌号6
	const store = ref(useMainStore()); //状态存储


	//键盘聚焦 隐藏默认键盘
	const onFocus = () => {
		keyboardShow.value = true;
	};

	//点击键盘文字
	const valChange = (val) => {
		// 将每次按键的值拼接到value变量中，注意+=写法
		plate.value += val;
		console.log(plate.value);
	};

	//点击删除
	const backspace = () => {
		// 删除plate的最后一个字符
		if (plate.value.length) {
			plate.value = plate.value.substr(0, plate.value.length - 1);
		}
		console.log(plate.value);
	};

	// 关闭逻辑
	const close = () => {
		keyboardShow.value = false;
	};

	//点击确认
	const confirm = () => {
		keyboardShow.value = false;
	};

	// 点击取消
	const cancel = () => {
		plate.value = "";
		keyboardShow.value = false;
	};

	//点击临牌
	// const temporary = () => {
	// 	plate.value = "临时牌照";
	// };


	//确认拍照 车架号
	const onConfirmCameraVIN = async (data) => {
		try {
			const base64Data = await readFileAsBase64(data.url); // 读取图片并转换为Base64编码
			isVinPhoto.value = false; // 更新组件状态
			let param = {
				'image': base64Data,
			};
			let formData = Object.keys(param).reduce((acc, key) => { // 将参数转换为 x-www-form-urlencoded 格式
				return acc + encodeURIComponent(key) + '=' + encodeURIComponent(param[key]) + '&';
			}, '').slice(0, -1);
			vin.value = await api_get_vin(formData); // 调用API
		} catch (error) {
			console.error('错误', error);
		}
	};


	//确认拍照 车牌号
	const onConfirmCameraPlate = async (data) => {
		try {
			const base64Data = await readFileAsBase64(data.url); // 读取图片并转换为Base64编码
			isPlatePhoto.value = false; // 更新组件状态
			let param = {
				'image': base64Data,
			};
			let formData = Object.keys(param).reduce((acc, key) => { // 将参数转换为 x-www-form-urlencoded 格式
				return acc + encodeURIComponent(key) + '=' + encodeURIComponent(param[key]) + '&';
			}, '').slice(0, -1);
			plate.value = await api_get_plate(formData); // 调用API识别
		} catch (error) {
			console.error('错误', error);
		}
	};

	// 读取图片并转换为Base64的函数
	const readFileAsBase64 = async (filePath) => {
		return new Promise((resolve, reject) => {
			uni.getFileSystemManager().readFile({
				filePath,
				encoding: 'base64', // 指定编码格式
				success(res) {
					resolve(res.data); // 返回完整的Base64字符串
				},
				fail(err) {
					reject(err); // 拒绝并传递错误信息
				}
			});
		});
	};

	//取消拍摄
	const onCancel = () => {
		isPlatePhoto.value = false;
		isVinPhoto.value = false;
	};

	//点击确定
	const to_next = async () => {
		console.log(plate.value, name.value, phone.value, vin.value);
		if (plate.value != '' && name.value != '' && vin.value != '') {
			if (phone.value.length != 11) {
				uni.showToast({
					title: "手机号长度错误",
					icon: 'error'
				});
				return;
			} else {
				let params = {
					carName: plate.value,
					customName: name.value,
					customPhone: phone.value,
					carVin: vin.value
				};

				try {
					let res = await api_saleOrder_add(params);
					store.value.orderId = res.data.saleId; //存储当前订单订单号
					uni.navigateTo({
						url: "/pages/salesman/new-order/order-improve/order-improve",
					})
				} catch (e) {
					uni.showToast({
						title: e.msg,
						icon: "none"
					});
				}
			}
		} else {
			uni.showToast({
				title: "请完善信息！",
				icon: 'error'
			});
			return;
		}
	};

	onShow(async () => {
		//返回时删除订单
		if (store.value.orderId) { //判断有没有订单,防止首次加载报错
			try {
				await api_saleOrder_delete({
					saleId: store.value.orderId
				});
				console.log("删除成功");
			} catch (e) {
				//TODO handle the exception
				uni.showToast({
					title: e.msg,
					icon: "none"
				});
			}
		}
		//并清空pinia存储的订单信息
		store.value.clear_oderInfo();
	});
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: $main-background-color;
		min-height: 100vh;

		.content {
			width: 700rpx;
			height: 750rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: space-between;
			margin-top: 400rpx;

			.info-input {
				width: 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 50rpx;

				.img {
					width: 60rpx;
					height: 50rpx;
					display: flex;
					justify-content: center;
					align-items: center;

					.pic {
						height: 50rpx;
					}
				}


				.ipt {
					width: 610rpx;
					height: 50rpx;
					border-bottom: 1rpx solid $border-color;
					display: flex;
					justify-content: space-between;
					align-items: center;

					input {
						flex-grow: 1;
						font-family: Alibaba_PuHuiTi_Thin;
						font-weight: 250;
						font-size: 34rpx;
						color: $font-primary-color;
					}

					.txt {
						font-family: Alibaba_PuHuiTi_Thin;
						font-weight: 250;
						font-size: 34rpx;
						color: $primary-color;
						margin-right: 10rpx;
					}

					.pic {
						height: 46rpx;
						padding: 0 8rpx;
					}
				}
			}

			.btn {
				margin-top: 200rpx;
				width: 700rpx;
				height: 75rpx;
				background: $primary-color;
				border-radius: 100rpx;
				border: none;
				color: white;
				font-weight: 300;
				font-size: 36rpx;
				font-family: Alibaba_PuHuiTi_Light;
				display: flex;
				justify-content: center;
				align-items: center;
				letter-spacing: 5rpx;
			}
		}
	}
</style>